/**
 * Created by Feil.Wang(wangfeilong@xuexibao.cn) on 2015/12/24.
 */
var Photo = require('../models/Photo');
var fs = require('fs');

module.exports = {
    list: function (req, res) {
        Photo.find({}, function (err, photos) {
            if (err) return next(err);
            res.render('photos/index', {
                title: '相册列表',
                userName: req.session.userName,
                photos: photos
            });
        })
    },
    form: function (req, res) {
        res.render('photos/upload', {
            title: '上传照片',
            userName: req.session.userName
        });
    },
    submit: function () {
        return function (req, res, next) {
            var img = req.file;
            var suffix = '.' + img.mimetype.split('/')[1];
            var name = req.body.name || img.filename;
            fs.rename(img.path, img.path + suffix, function (err) {
                if (err)return next(err);
                Photo.create({
                    name: name,
                    path: '/photos/' + img.filename + suffix
                }, function (err) {
                    if (err) return next(err);
                    res.redirect('/');
                });
            });
        }
    }
};